<template>
  <div class="app-container">
    <!-- 操作区域 -->
    <div class="operation-container">
      <el-button type="success" icon="el-icon-plus" @click="createBatch">
        创建批次
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="showAddMatchDialog">
        添加赛事
      </el-button>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true" class="filter-form">
        <el-form-item label="赛事类型">
          <el-select v-model="listQuery.type" placeholder="选择赛事类型" clearable @change="handleFilterChange">
            <el-option label="足球" :value="1" />
            <el-option label="篮球" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleFilterChange">
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 添加赛事弹出框 -->
    <el-dialog
      title="添加赛事"
      :visible.sync="addMatchDialogVisible"
      width="60%"
      :before-close="closeAddMatchDialog"
      :close-on-click-modal="false"
    >
      <el-form :model="addMatchForm" label-width="100px">
        <el-form-item label="主队搜索">
          <el-input
            v-model="searchTeamName"
            placeholder="输入队伍名称搜索"
            style="width: 300px;"
            @input="searchMatches"
          />
        </el-form-item>
      </el-form>

      <!-- 搜索结果列表 -->
      <div v-if="searchResults.length > 0" class="search-results">
        <h4>搜索结果：</h4>
        <div class="match-options">
          <el-radio-group v-model="selectedMatch" @change="handleMatchSelect">
            <el-radio-button
              v-for="match in searchResults"
              :key="match.match_id"
              :label="match"
              class="match-option"
            >
              <div class="match-info">
                <div class="match-competition">{{ match.competition_name }}</div>
                <div class="match-teams">{{ match.home_team_name }} VS {{ match.away_team_name }}</div>
                <div class="match-time">{{ match.match_time }}</div>
              </div>
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddMatchDialog">取消</el-button>
        <el-button type="primary" :disabled="!selectedMatch" @click="confirmAddMatch">确定添加</el-button>
      </div>
    </el-dialog>

    <!-- 卡片式布局 -->
    <div v-loading="listLoading" class="match-cards-container">
      <!-- 有数据时显示列表 -->
      <template v-if="list && list.length > 0">
        <div v-for="match in list" :key="match.id || match.sporttery_id" class="match-card">
          <!-- 联赛和队伍信息 -->
          <div class="match-header">
            <div class="league-info">{{ match.competition_name }}</div>
            <div class="teams-info">{{ match.home_team_name }} VS {{ match.away_team_name }}</div>
            <span class="sport-type">{{ match.type == 1 ? '足球' : '篮球' }}</span>
            <!-- 选择状态指示器 -->
            <div v-if="match.predictionType && match.selectedOdds.length > 0" class="selection-indicator">
              <i class="el-icon-check" />
              <span>已选择</span>
            </div>
          </div>

          <!-- 比赛详情和赔率 -->
          <div class="match-content">
            <!-- 左侧：比赛信息 -->
            <div class="match-details">
              <div class="match-id">{{ match.sporttery_str || '暂无' }}</div>
              <div class="match-time">{{ match.match_time }}</div>
            </div>

            <!-- 右侧：赔率信息 -->
            <div class="odds-section">
              <!-- 胜平负赔率 -->
              <div v-if="match.had && match.had.h" class="odds-group">
                <div class="odds-item">
                  <span class="odds-label-text">胜</span>
                  <span class="odds-value">{{ match.had.h || '-' }}</span>
                </div>
                <div class="odds-item">
                  <span class="odds-label-text">平</span>
                  <span class="odds-value">{{ match.had.d || '-' }}</span>
                </div>
                <div class="odds-item">
                  <span class="odds-label-text">负</span>
                  <span class="odds-value">{{ match.had.a || '-' }}</span>
                </div>
              </div>

              <!-- 让球胜平负赔率 -->
              <div v-if="match.hhad && match.hhad.h" class="odds-group">
                <div class="odds-item">
                  <span class="odds-label-text">让球胜</span>
                  <span class="odds-value">{{ match.hhad.h || '-' }}</span>
                </div>
                <div class="odds-item">
                  <span class="odds-label-text">让球平</span>
                  <span class="odds-value">{{ match.hhad.d || '-' }}</span>
                </div>
                <div class="odds-item">
                  <span class="odds-label-text">让球负</span>
                  <span class="odds-value">{{ match.hhad.a || '-' }}</span>
                </div>
              </div>

              <!-- 大小球赔率 -->
              <div v-if="match.haa && match.haa.o" class="odds-group">
                <div class="odds-item">
                  <span class="odds-label-text">大球</span>
                  <span class="odds-value">{{ match.haa.o || '-' }}</span>
                </div>
                <div class="odds-item">
                  <span class="odds-label-text">小球</span>
                  <span class="odds-value">{{ match.haa.u || '-' }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 预测分类选择 -->
          <div class="prediction-section">
            <div class="prediction-label">预测分类：</div>
            <el-radio-group v-model="match.predictionType" size="mini" @change="handlePredictionChange(match)">
              <el-radio v-for="item in predictionTypes" :key="item.id" :label="item.id">{{ item.text }}</el-radio>
            </el-radio-group>
          </div>

          <!-- 赔率选择区域 -->
          <div v-if="match.predictionType" class="odds-selection-area">
            <div class="odds-label">
              选择赔率：
              <span v-if="match.selectedOdds.length > 0" class="selected-count">
                (已选择 {{ match.selectedOdds.length }}/2)
              </span>
              <div v-if="match.selectedOdds.length > 0" class="selected-items">
                <span v-for="(odds, index) in match.selectedOdds" :key="index" class="selected-item">
                  {{ odds.label }}({{ odds.value }})
                </span>
              </div>
            </div>
            <el-checkbox-group v-model="match.selectedOdds" :max="2" @change="handleOddsSelectionChange(match)">
              <div class="odds-options">
                <el-checkbox-button
                  v-for="(odds, index) in getFilteredMatchOdds(match)"
                  :key="index"
                  :label="odds"
                  :disabled="!canSelectOdds(odds, match)"
                  class="odds-checkbox"
                  :class="{ 'odds-disabled': !canSelectOdds(odds, match) }"
                >
                  <div class="odds-content">
                    <div class="odds-name">{{ odds.label }}</div>
                    <div class="odds-value">{{ odds.value }}</div>
                    <!-- 选中标记 -->
                    <div v-if="isOddsSelected(match, odds)" class="selected-mark">
                      <i class="el-icon-check" />
                    </div>
                    <!-- 禁用标记 -->
                    <div v-if="!canSelectOdds(odds, match)" class="disabled-mark">
                      <i class="el-icon-lock" />
                    </div>
                  </div>
                </el-checkbox-button>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </template>

      <!-- 空状态显示 -->
      <div v-else-if="!listLoading && (!list || list.length === 0)" class="empty-state">
        <div class="empty-content">
          <div class="empty-icon">
            <i class="el-icon-trophy" />
          </div>
          <div class="empty-text">
            <h3>暂无赛事数据</h3>
            <p>当前筛选条件下没有找到相关赛事</p>
          </div>
          <div class="empty-actions">
            <el-button type="primary" @click="resetFilter">
              <i class="el-icon-refresh" />
              重置筛选条件
            </el-button>
            <el-button type="success" @click="showAddMatchDialog">
              <i class="el-icon-plus" />
              添加赛事
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 固定定位的已选择比赛展示区域 -->
    <div v-if="selectedMatchesSummary.length > 0" class="fixed-selection-panel">
      <div class="selection-panel-header">
        <span class="selection-title">
          <i class="el-icon-check" />
          已选择比赛 ({{ selectedMatchesSummary.length }})
        </span>
        <el-button type="text" icon="el-icon-close" class="close-btn" @click="clearAllSelections">
          清空
        </el-button>
      </div>
      <div class="selection-panel-content">
        <div
          v-for="item in selectedMatchesSummary"
          :key="item.matchId"
          class="selection-item"
        >
          <div class="selection-item-main">
            <div class="selection-item-teams">{{ item.teams }}</div>
            <div class="selection-item-details">
              <span class="selection-item-type">{{ item.predictionTypeName }}</span>
              <span class="selection-item-odds">{{ item.oddsText }}</span>
            </div>
          </div>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="mini"
            class="remove-btn"
            @click="removeSelection(item.matchId)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getConfigList, hqOddsData, getAiMatchList, matchAdd, hqMatcheList, piciAdd } from '../../../libs/api'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

const statusOptions = [
  { key: 'upcoming', display_name: '未开始' },
  { key: 'live', display_name: '进行中' },
  { key: 'finished', display_name: '已结束' },
  { key: 'cancelled', display_name: '已取消' }
]

const leagueOptions = [
  { key: '英超', display_name: '英超' },
  { key: '西甲', display_name: '西甲' },
  { key: '德甲', display_name: '德甲' },
  { key: '意甲', display_name: '意甲' },
  { key: '法甲', display_name: '法甲' },
  { key: '欧冠', display_name: '欧冠' },
  { key: '欧联', display_name: '欧联' },
  { key: '中超', display_name: '中超' },
  { key: '日职', display_name: '日职' },
  { key: '韩职', display_name: '韩职' }
]

export default {
  name: 'MatchList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        upcoming: 'info',
        live: 'success',
        finished: 'primary',
        cancelled: 'danger'
      }
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = {
        upcoming: '未开始',
        live: '进行中',
        finished: '已结束',
        cancelled: '已取消'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      syncLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        team_name: undefined,
        league: undefined,
        status: undefined,
        data_source: undefined,
        date_range: undefined,
        type: 1
      },
      leagueOptions: leagueOptions,
      statusOptions: statusOptions,
      predictionTypes: [], // 预测分类列表
      // 添加赛事相关数据
      addMatchDialogVisible: false,
      searchTeamName: '',
      searchResults: [],
      selectedMatch: null,
      // 存储键名
      storageKey: 'matchList_selections',
      // 用于触发计算属性更新的响应式变量
      selectionUpdateTrigger: 0
    }
  },
  computed: {
    // 计算已选择的比赛摘要（从 localStorage 读取所有已选择的比赛，包括其他页面的）
    selectedMatchesSummary() {
      // 依赖 selectionUpdateTrigger 来触发更新
      this.selectionUpdateTrigger

      try {
        const storageKey = `${this.storageKey}_type${this.listQuery.type || 1}`
        const savedSelections = this.loadSelections(storageKey)

        if (!savedSelections || Object.keys(savedSelections).length === 0) {
          return []
        }

        // 将存储的选择数据转换为展示格式
        const result = Object.keys(savedSelections).map(matchId => {
          const selection = savedSelections[matchId]
          if (!selection || !selection.predictionType || !selection.selectedOdds || !Array.isArray(selection.selectedOdds) || selection.selectedOdds.length === 0) {
            return null
          }

          const predictionTypeName = this.predictionTypes.find(type => type.id === selection.predictionType)?.text || '未知'
          const oddsText = selection.selectedOdds.map(odds => `${odds.label}(${odds.value})`).join('、')
          return {
            matchId: String(matchId),
            teams: selection.home_team_name && selection.away_team_name
              ? `${selection.home_team_name} VS ${selection.away_team_name}`
              : '未知队伍',
            competitionName: selection.competition_name || '未知联赛',
            predictionType: selection.predictionType,
            predictionTypeName: predictionTypeName,
            oddsText: oddsText,
            selectedOdds: selection.selectedOdds
          }
        }).filter(item => item !== null)

        return result
      } catch (error) {
        console.error('获取已选择比赛摘要失败:', error)
        return []
      }
    }
  },
  created() {
    this.getConfigListData()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true

      // 调用getAiMatchList接口
      getAiMatchList({
        page: this.listQuery.page,
        page_size: this.listQuery.limit,
        type: this.listQuery.type
      }).then(res => {
        console.log('获取AI赛事列表:', res)

        if (res.data && res.data.data) {
          // 获取保存的选择数据（使用当前类型）
          const storageKey = `${this.storageKey}_type${this.listQuery.type || 1}`
          const savedSelections = this.loadSelections(storageKey)

          // 为每个赛事添加预测分类和赔率选择相关属性
          const matchesWithPrediction = res.data.data.map(match => {
            const matchId = String(match.match_id || match.sporttery_id || '')
            const savedSelection = savedSelections[matchId]

            return {
              ...match,
              predictionType: savedSelection ? savedSelection.predictionType : null, // 预测分类，从存储中恢复
              selectedOdds: savedSelection ? (savedSelection.selectedOdds || []) : [] // 选中的赔率，从存储中恢复
            }
          })

          this.list = matchesWithPrediction
          this.total = res.data.total || 0
        } else {
          this.list = []
          this.total = 0
        }

        this.listLoading = false
      }).catch(error => {
        console.error('获取AI赛事列表失败:', error)
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },

    // 时间格式化
    formatMatchTime(timeStr) {
      if (!timeStr) return '-'
      try {
        const date = new Date(timeStr)
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${month}-${day} ${hours}:${minutes}`
      } catch (error) {
        console.warn('时间格式化失败:', timeStr, error)
        return timeStr
      }
    },

    // 处理预测分类变更
    handlePredictionChange(match) {
      // 清空之前选中的赔率
      match.selectedOdds = []
      console.log('预测分类变更:', match.predictionType, match)
      // 保存选择到本地存储
      this.saveSelection(match)
    },

    // 处理赔率选择变更
    handleOddsSelectionChange(match) {
      console.log('赔率选择变更:', match.selectedOdds, match)
      // 保存选择到本地存储
      this.saveSelection(match)
    },

    // 获取赛事的赔率选项
    getMatchOdds(match) {
      if (!match.predictionType) return []

      // 如果已经有缓存的赔率数据，直接返回
      if (match.cachedOdds && match.cachedOdds[match.predictionType]) {
        return match.cachedOdds[match.predictionType]
      }

      // 使用本地数据作为备选方案
      const oddsData = this.getLocalOddsData(match, match.predictionType)

      // 异步获取API数据
      this.fetchOddsFromAPI(match, match.predictionType)

      return oddsData
    },

    // 获取过滤后的赔率选项
    getFilteredMatchOdds(match) {
      const allOdds = this.getMatchOdds(match)
      return allOdds.filter(odds => this.shouldShowOdds(odds, match))
    },

    // 获取本地赔率数据
    getLocalOddsData(match, predictionType) {
      const oddsData = []

      if (predictionType === 1) { // 胜平负
        const had = match.had || {}
        oddsData.push(
          { label: '胜', value: had.h || '-', is_recommend: false },
          { label: '平', value: had.d || '-', is_recommend: false },
          { label: '负', value: had.a || '-', is_recommend: false }
        )
      } else if (predictionType === 2) { // 让球胜平负
        const hhad = match.hhad || {}
        oddsData.push(
          { label: '让球胜', value: hhad.h || '-', is_recommend: false },
          { label: '让球平', value: hhad.d || '-', is_recommend: false },
          { label: '让球负', value: hhad.a || '-', is_recommend: false }
        )
      } else if (predictionType === 3) { // 总进球
        const ttg = match.ttg || {}
        oddsData.push(
          { label: '0球', value: ttg.s0 || '-', is_recommend: false },
          { label: '1球', value: ttg.s1 || '-', is_recommend: false },
          { label: '2球', value: ttg.s2 || '-', is_recommend: false },
          { label: '3球', value: ttg.s3 || '-', is_recommend: false },
          { label: '4球', value: ttg.s4 || '-', is_recommend: false },
          { label: '5球', value: ttg.s5 || '-', is_recommend: false },
          { label: '6球+', value: ttg.s6 || '-', is_recommend: false }
        )
      } else if (predictionType === 4) { // 比分
        const crs = match.crs || {}
        oddsData.push(
          { label: '1:0', value: crs.h1_0 || '-', is_recommend: false },
          { label: '2:0', value: crs.h2_0 || '-', is_recommend: false },
          { label: '2:1', value: crs.h2_1 || '-', is_recommend: false },
          { label: '0:1', value: crs.a0_1 || '-', is_recommend: false },
          { label: '0:2', value: crs.a0_2 || '-', is_recommend: false },
          { label: '平局', value: crs.d || '-', is_recommend: false }
        )
      } else if (predictionType === 5) { // 半全场
        const hafu = match.hafu || {}
        oddsData.push(
          { label: '胜胜', value: hafu.hh || '-', is_recommend: false },
          { label: '胜平', value: hafu.hd || '-', is_recommend: false },
          { label: '胜负', value: hafu.ha || '-', is_recommend: false },
          { label: '平胜', value: hafu.dh || '-', is_recommend: false },
          { label: '平平', value: hafu.dd || '-', is_recommend: false },
          { label: '平负', value: hafu.da || '-', is_recommend: false },
          { label: '负胜', value: hafu.ah || '-', is_recommend: false },
          { label: '负平', value: hafu.ad || '-', is_recommend: false },
          { label: '负负', value: hafu.aa || '-', is_recommend: false }
        )
      }

      return oddsData
    },

    // 从API获取赔率数据
    fetchOddsFromAPI(match, predictionType) {
      if (!match.match_id) return

      hqOddsData({
        match_id: match.match_id,
        lx: this.listQuery.type || 1, // 根据当前选择的赛事类型：1是足球，2是篮球
        lot_lx: predictionType
      }).then(res => {
        console.log('获取赔率数据:', res)
        if (res.data && res.data.odds) {
          // 缓存赔率数据
          if (!match.cachedOdds) {
            this.$set(match, 'cachedOdds', {})
          }

          let oddsData = []
          if (predictionType === 1) {
            // 胜平负数据是二维数组，需要合并
            if (Array.isArray(res.data.odds) && res.data.odds.length > 0) {
              if (Array.isArray(res.data.odds[0])) {
                // 二维数组，需要合并
                oddsData = res.data.odds.flat()
              } else {
                // 一维数组
                oddsData = res.data.odds
              }
            }
          } else {
            // 其他类型（包括竞彩）的处理
            if (Array.isArray(res.data.odds) && res.data.odds.length > 0) {
              if (Array.isArray(res.data.odds[0])) {
                // 二维数组，根据hqinformation的逻辑，直接使用整个数组
                oddsData = res.data.odds.flat()
              } else {
                // 一维数组
                oddsData = res.data.odds
              }
            }
          }

          console.log('预测分类ID:', predictionType)
          console.log('原始赔率数据:', res.data.odds)
          console.log('数据类型:', Array.isArray(res.data.odds) ? '数组' : '非数组')
          if (Array.isArray(res.data.odds) && res.data.odds.length > 0) {
            console.log('第一个元素类型:', Array.isArray(res.data.odds[0]) ? '数组' : '非数组')
            console.log('第一个元素内容:', res.data.odds[0])
          }
          console.log('处理后的赔率数据:', oddsData)

          // 转换数据格式
          const formattedOdds = oddsData.map(item => ({
            label: item.label || item.name || '未知',
            value: item.value || item.odds || '-',
            is_recommend: false
          }))

          this.$set(match.cachedOdds, predictionType, formattedOdds)
        }
      }).catch(error => {
        console.error('获取赔率数据失败:', error)
      })
    },

    // 检查赔率是否被选中
    isOddsSelected(match, odds) {
      if (!match.selectedOdds || !Array.isArray(match.selectedOdds)) {
        return false
      }

      const isSelected = match.selectedOdds.some(selected => {
        // 比较对象引用或者比较关键属性
        if (selected === odds) {
          return true
        }

        // 如果对象引用不同，比较关键属性
        const isMatch = selected.label === odds.label && selected.value === odds.value

        // 添加调试信息
        console.log('比较选中状态:', {
          selectedLabel: selected.label,
          oddsLabel: odds.label,
          selectedValue: selected.value,
          oddsValue: odds.value,
          isMatch: isMatch
        })

        return isMatch
      })

      return isSelected
    },

    // 判断是否应该显示赔率选项
    shouldShowOdds(odds, match) {
      // 所有赔率选项都显示，选中控制由 canSelectOdds 方法处理
      return true
    },

    // 判断赔率选项是否可以被选中
    canSelectOdds(odds, match) {
      // 如果赔率label是"让球"，需要检查预测分类
      if (odds.label === '让球') {
        const selectedPredictionType = this.predictionTypes.find(item => item.id === match.predictionType)

        // 如果找不到对应的预测分类配置，可以选中
        if (!selectedPredictionType) {
          return true
        }

        // 如果预测分类的text是"竞彩"，则不能选中
        if (selectedPredictionType.text === '竞彩') {
          return false
        }
        return true
      }

      // 其他情况都可以选中
      return true
    },

    // 获取配置列表数据
    getConfigListData() {
      getConfigList({}).then(res => {
        console.log('获取配置数据:', res)
        if (res.data && res.data.lotLxList) {
          this.predictionTypes = res.data.lotLxList
        }
      }).catch(error => {
        console.error('获取配置数据失败:', error)
      })
    },

    // 创建批次
    createBatch() {
      try {
        // 从 localStorage 读取所有已选择的比赛（包括所有页面的）
        const storageKey = `${this.storageKey}_type${this.listQuery.type || 1}`
        const savedSelections = this.loadSelections(storageKey)

        if (!savedSelections || Object.keys(savedSelections).length === 0) {
          this.$message.warning('请先选择至少一个赛事的预测分类和赔率')
          return
        }

        // 将存储的选择数据转换为创建批次所需的格式
        const selectedMatches = Object.keys(savedSelections).map(matchId => {
          const selection = savedSelections[matchId]

          // 验证数据完整性
          if (!selection || !selection.predictionType || !selection.selectedOdds || !Array.isArray(selection.selectedOdds) || selection.selectedOdds.length === 0) {
            return null
          }

          const predictionTypeName = this.predictionTypes.find(type => type.id === selection.predictionType)?.text || '未知'

          return {
            match_id: selection.match_id || matchId,
            competition_name: selection.competition_name || '未知联赛',
            home_team_name: selection.home_team_name || '未知',
            away_team_name: selection.away_team_name || '未知',
            start_time: selection.start_time_value,
            prediction_type: selection.predictionType,
            prediction_type_name: predictionTypeName,
            selected_odds: selection.selectedOdds.map(odds => ({
              label: odds.label,
              value: odds.value,
              is_recommend: odds.is_recommend || false
            })),
            all_odds: selection.all_odds || selection.selectedOdds.map(odds => ({
              label: odds.label,
              value: odds.value,
              is_recommend: odds.is_recommend || false
            }))
          }
        }).filter(item => item !== null)

        console.log('=== 创建批次 - 选中的赛事数据 ===')
        console.log('选中赛事数量:', selectedMatches.length)
        console.log('详细数据:', selectedMatches)

        if (selectedMatches.length === 0) {
          this.$message.warning('请先选择至少一个赛事的预测分类和赔率')
          return
        }

        piciAdd({
          array: selectedMatches
        }).then(res => {
          if (res.code === 1) {
            this.$message.success(`成功创建批次，共选中 ${selectedMatches.length} 个赛事`)
            // 创建成功后清空选择
            this.clearAllSelectionsSilently()
          } else {
            this.$message.error(res.message || '创建批次失败')
          }
        }).catch(error => {
          console.error('创建批次失败:', error)
          this.$message.error('创建批次失败，请稍后重试')
        })
      } catch (error) {
        console.error('创建批次异常:', error)
        this.$message.error('创建批次失败，请稍后重试')
      }
    },

    // 显示添加赛事弹出框
    showAddMatchDialog() {
      this.addMatchDialogVisible = true
      this.searchTeamName = ''
      this.searchResults = []
      this.selectedMatch = null
    },

    // 关闭添加赛事弹出框
    closeAddMatchDialog() {
      this.addMatchDialogVisible = false
      this.searchTeamName = ''
      this.searchResults = []
      this.selectedMatch = null
    },

    // 搜索赛事
    searchMatches() {
      if (!this.searchTeamName.trim()) {
        this.searchResults = []
        return
      }

      hqMatcheList({
        page: 1,
        limit: 20,
        lx: this.listQuery.type || 1, // 根据当前选择的赛事类型：1是足球，2是篮球
        name: this.searchTeamName
      }).then(res => {
        console.log('搜索赛事结果:', res)
        if (res.data && res.data.list && res.data.list.data) {
          this.searchResults = res.data.list.data
        } else {
          this.searchResults = []
        }
      }).catch(error => {
        console.error('搜索赛事失败:', error)
        this.searchResults = []
      })
    },

    // 处理赛事选择
    handleMatchSelect(match) {
      console.log('选择赛事:', match)
      this.selectedMatch = match
    },

    // 确认添加赛事
    confirmAddMatch() {
      if (!this.selectedMatch) {
        this.$message.warning('请先选择一个赛事')
        return
      }

      // 调用matchAdd接口
      matchAdd({
        match_id: this.selectedMatch.match_id
      }).then(res => {
        console.log('添加赛事结果:', res)
        this.$message.success('赛事添加成功')
        this.closeAddMatchDialog()
        // 刷新列表
        this.getList()
      }).catch(error => {
        console.error('添加赛事失败:', error)
        this.$message.error('添加赛事失败')
      })
    },

    // 筛选条件变化处理
    handleFilterChange() {
      this.listQuery.page = 1 // 重置到第一页
      this.getList()
    },

    // 重置筛选条件
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20,
        team_name: undefined,
        league: undefined,
        status: undefined,
        data_source: undefined,
        date_range: undefined,
        type: 1 // 默认选择足球
      }
      this.getList()
    },

    // 保存选择到本地存储
    saveSelection(match) {
      try {
        const matchId = String(match.match_id || match.sporttery_id || '')
        if (!matchId || matchId === 'undefined' || matchId === 'null') {
          console.warn('保存选择失败：无法获取 matchId', match)
          return
        }

        // 使用类型和ID组合作为唯一键
        const storageKey = `${this.storageKey}_type${this.listQuery.type || 1}`
        const savedSelections = this.loadSelections(storageKey)

        // 如果有选择，则保存；如果没有选择，则删除该记录的存储
        if (match.predictionType && match.selectedOdds && match.selectedOdds.length > 0) {
          // 获取该赛事的全部赔率选项（用于创建批次时需要）
          const allOdds = this.getMatchOdds(match)

          savedSelections[matchId] = {
            predictionType: match.predictionType,
            selectedOdds: match.selectedOdds.map(odds => ({
              label: odds.label,
              value: odds.value,
              is_recommend: odds.is_recommend || false
            })),
            // 保存比赛基本信息，用于在其他页面也能显示和创建批次
            match_id: match.match_id || match.sporttery_id,
            home_team_name: match.home_team_name,
            away_team_name: match.away_team_name,
            competition_name: match.competition_name,
            start_time_value: match.start_time_value,
            // 保存所有赔率选项，用于创建批次
            all_odds: allOdds.map(odds => ({
              label: odds.label,
              value: odds.value,
              is_recommend: odds.is_recommend || false
            }))
          }
          console.log('保存选择成功:', matchId, savedSelections[matchId])
        } else {
          // 如果没有选择，删除该记录
          delete savedSelections[matchId]
          console.log('删除选择:', matchId)
        }

        // 保存到 localStorage
        localStorage.setItem(storageKey, JSON.stringify(savedSelections))
        // 触发计算属性更新
        this.selectionUpdateTrigger++
      } catch (error) {
        console.error('保存选择失败:', error)
      }
    },

    // 从本地存储加载选择
    loadSelections(storageKey) {
      try {
        const key = storageKey || `${this.storageKey}_type${this.listQuery.type || 1}`
        const saved = localStorage.getItem(key)
        return saved ? JSON.parse(saved) : {}
      } catch (error) {
        console.error('加载选择失败:', error)
        return {}
      }
    },

    // 移除单个选择
    removeSelection(matchId) {
      try {
        const storageKey = `${this.storageKey}_type${this.listQuery.type || 1}`
        const savedSelections = this.loadSelections(storageKey)

        // 确保 matchId 是字符串
        const matchIdStr = String(matchId)

        // 从存储中删除
        delete savedSelections[matchIdStr]
        localStorage.setItem(storageKey, JSON.stringify(savedSelections))

        // 如果该比赛在当前页面的列表中，也更新列表中的状态
        if (this.list && this.list.length > 0) {
          const match = this.list.find(m => String(m.match_id || m.sporttery_id) === matchIdStr)
          if (match) {
            match.predictionType = null
            match.selectedOdds = []
          }
        }

        // 触发计算属性更新
        this.selectionUpdateTrigger++
        this.$message.success('已移除选择')
      } catch (error) {
        console.error('移除选择失败:', error)
        this.$message.error('移除选择失败')
      }
    },

    // 清空所有选择
    clearAllSelections() {
      this.$confirm('确定要清空所有已选择的比赛吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearAllSelectionsSilently()
        this.$message.success('已清空所有选择')
      }).catch(() => {
        // 用户取消操作
      })
    },

    // 静默清空所有选择（不显示确认对话框）
    clearAllSelectionsSilently() {
      if (this.list && this.list.length > 0) {
        this.list.forEach(match => {
          match.predictionType = null
          match.selectedOdds = []
        })
      }
      // 清除当前类型的存储
      const storageKey = `${this.storageKey}_type${this.listQuery.type || 1}`
      localStorage.removeItem(storageKey)
      // 触发计算属性更新
      this.selectionUpdateTrigger++
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.app-container {
  padding: 20px;
}

/* 操作区域样式 */
.operation-container {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  display: flex;
  gap: 10px;
}

/* 筛选条件区域样式 */
.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 15px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

.filter-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 添加赛事弹出框样式 */
.search-results {
  margin-top: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.search-results h4 {
  margin-bottom: 15px;
  color: #333;
}

.match-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.match-option {
  margin: 0 !important;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

.match-option:hover {
  border-color: #409eff;
}

.match-option.is-active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.match-info {
  padding: 10px;
  text-align: center;
  min-width: 200px;
}

.match-competition {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.match-teams {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.match-time {
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  text-align: right;
}

.match-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

/* 空状态样式 */
.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 40px 20px;
}

.empty-content {
  text-align: center;
  max-width: 400px;
}

.empty-icon {
  font-size: 80px;
  color: #c0c4cc;
  margin-bottom: 20px;
  opacity: 0.6;
}

.empty-text h3 {
  font-size: 18px;
  color: #606266;
  margin: 0 0 10px 0;
  font-weight: 500;
}

.empty-text p {
  font-size: 14px;
  color: #909399;
  margin: 0 0 30px 0;
  line-height: 1.5;
}

.empty-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.empty-actions .el-button {
  padding: 10px 20px;
  border-radius: 6px;
  font-weight: 500;
}

.empty-actions .el-button i {
  margin-right: 5px;
}

.match-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  word-wrap: break-word;
  word-break: break-word;
}

.match-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.match-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  min-height: 40px;
  gap: 10px;
}

.sport-type {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  min-width: 40px;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.sport-type:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

.league-info {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 120px;
}

.teams-info {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
  margin: 0 auto;
}

.selection-indicator {
  display: flex;
  align-items: center;
  gap: 5px;
  background: #67c23a;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(10px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.match-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 15px;
}

.match-details {
  flex: 1;
  min-width: 120px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.match-id {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.match-time {
  font-size: 14px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.odds-section {
  display: flex;
  gap: 15px;
  flex-shrink: 0;
  min-width: 200px;
}

.odds-group {
  display: flex;
  gap: 10px;
}

.odds-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 60px;
}

.odds-label-text {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.odds-value {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
}

/* 预测分类和赔率选择样式 */
.prediction-section {
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.prediction-label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.odds-selection-area {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.odds-label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.selected-count {
  color: #67c23a;
  font-weight: 600;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}

.selected-items {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.selected-item {
  background: #67c23a;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.odds-options {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  max-width: 100%;
  overflow: hidden;
}

.odds-checkbox {
  position: relative;
}

.odds-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding: 10px;
  text-align: center;
  overflow: hidden;
  word-wrap: break-word;
  word-break: break-word;
}

.odds-name {
  font-size: 12px;
  font-weight: 500;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

.odds-value {
  font-size: 14px;
  font-weight: 600;
  color: #e6a23c;
}

.selected-mark {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  background: #67c23a;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  animation: bounceIn 0.3s ease-out;
}

@keyframes bounceIn {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

/* 禁用状态的赔率选项样式 */
.odds-disabled .el-checkbox-button__inner {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
  opacity: 0.6;
}

.odds-disabled .el-checkbox-button__inner:hover {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #c0c4cc !important;
}

.odds-disabled .odds-content {
  opacity: 0.6;
}

.disabled-mark {
  position: absolute;
  top: -5px;
  left: -5px;
  width: 20px;
  height: 20px;
  background: #c0c4cc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 预测分类单选按钮样式优化 */
.prediction-section .el-radio {
  margin-right: 15px;
  margin-bottom: 8px;
}

.prediction-section .el-radio__label {
  font-size: 13px;
  color: #606266;
  padding-left: 8px;
}

.prediction-section .el-radio__input.is-checked .el-radio__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.prediction-section .el-radio__input.is-checked + .el-radio__label {
  color: #409eff;
  font-weight: 600;
}

/* 赔率选择复选框样式优化 */
.odds-checkbox .el-checkbox-button__inner {
  border: 1px solid #dcdfe6;
  background: #fff;
  color: #606266;
  padding: 15px 20px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background: #fff;
  transition: all 0.3s;
  min-width: 80px;
  text-align: center;
}

.odds-checkbox-button .el-checkbox-button__inner:hover {
  border-color: #409eff;
  background: #f5f7fa;
}

.odds-checkbox-button.is-checked .el-checkbox-button__inner {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.odds-item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.odds-label {
  font-size: 14px;
  font-weight: 500;
}

.odds-value {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .match-cards-container {
    grid-template-columns: 1fr;
  }

  .match-content {
    flex-direction: column;
    gap: 10px;
  }

  .match-details {
    min-width: auto;
  }

  .odds-section {
    min-width: auto;
    flex-direction: column;
    gap: 10px;
  }

  .odds-group,
  .odds-single-group {
    flex-direction: column;
  }

  .odds-checkbox-button {
    width: 100%;
  }

  .odds-checkbox-button .el-checkbox-button__inner {
    width: 100%;
  }
}

/* 全屏时的样式优化 */
@media (min-width: 1920px) {
  .match-cards-container {
    grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
    max-width: 100%;
  }

  .match-card {
    max-width: 100%;
    overflow: hidden;
  }

  .teams-info {
    max-width: 300px;
  }

  .league-info {
    max-width: 150px;
  }

  .odds-options {
    grid-template-columns: repeat(4, 1fr);
  }
}

/* 超宽屏优化 */
@media (min-width: 2560px) {
  .match-cards-container {
    grid-template-columns: repeat(auto-fill, minmax(600px, 1fr));
  }

  .teams-info {
    max-width: 400px;
  }

  .league-info {
    max-width: 200px;
  }
}

/* 固定定位的已选择比赛展示面板 */
.fixed-selection-panel {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  width: 320px;
  max-height: 80vh;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.selection-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
  border-bottom: 1px solid #e4e7ed;
}

.selection-title {
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selection-title i {
  font-size: 18px;
}

.close-btn {
  color: white;
  padding: 0;
  font-size: 14px;
}

.close-btn:hover {
  color: #f0f0f0;
}

.selection-panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  max-height: calc(80vh - 60px);
}

.selection-panel-content::-webkit-scrollbar {
  width: 6px;
}

.selection-panel-content::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.selection-panel-content::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.selection-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.3s;
}

.selection-item:hover {
  background: #ecf5ff;
  border-color: #409eff;
}

.selection-item-main {
  flex: 1;
  min-width: 0;
}

.selection-item-teams {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selection-item-details {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.selection-item-type {
  font-size: 12px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.selection-item-odds {
  font-size: 12px;
  color: #67c23a;
  background: #f0f9ff;
  padding: 2px 8px;
  border-radius: 12px;
}

.remove-btn {
  color: #f56c6c;
  padding: 0 5px;
  font-size: 16px;
  flex-shrink: 0;
}

.remove-btn:hover {
  color: #f78989;
}

/* 响应式：小屏幕时调整固定面板位置 */
@media (max-width: 768px) {
  .fixed-selection-panel {
    right: 10px;
    width: 280px;
    max-height: 70vh;
  }
}
</style>
